<template>
  <div class="alarmConfiguration zy-content" :style="{ height: containerHeight + 'px' }">
    <div class="left-side" style="flex: 0 0 40%;">
      <!-- 左侧内容 -->
      <div class="left-content">
        <h2>生产关系设置</h2>
        <div class="button_but_top">
          <Button type="primary"
          :disabled="lineData.length>0"
          @click="ShowModal('add', { level: 0 })">新增节点</Button>
          <!-- <Button type="error" size="small" @click="delShow('','all')">批量删除</Button> -->

        </div>
        <Table
  ref="selection"
  @on-selection-change="handleSelectionChange"
  row-key="id"
  :columns="columns"
  :data="lineData"
  border
  @on-column-width-resize="onDragEnd"
>
          <template slot-scope="{ row }" slot="action">
            <div class="button_but">
              <Button type="text" size="small" @click="ShowModal('edit', row)">修改</Button>
              <Button type="text" size="small" @click="ShowModal('next', row)" v-if="row.level < 3">添加下级</Button>
              <Button type="text" size="small" @click="delShow(row,'isAll')">删除</Button>
            </div>
          </template>

        </Table>
      </div>
    </div>
    <div class="right-side" style="flex: 1;">
      <!-- 右侧内容 -->
      <div class="right-content">
        <h2>产线结构</h2>
        <div ref="chart" style="width: 100%;height:400px;"></div>
      </div>
    </div>
    <CreateOrUpdateModal :visible="isVisible" :form="form" :title="title" :handleAddSubmit="handleAddSubmit"
      :closeModals="closeModals" />
    <Modal :mask-closable="false" v-model="deleteShow" title="删除" class="modal-title-layout">
      <p class="title">
        <span>是否确认删除?</span>
      </p>
      <div slot="footer">

        <Button type="default" @click="deleteShow = false">取消</Button>
        <Button type="primary" @click="handleDeleteSure">确定</Button>
      </div>
    </Modal>
  </div>

</template>

<script>
import {
  lineAll, addLine, editLine, deltLine
} from '@/api/dataBasic/productionLine';
import search from '@/components/curd/searchList.vue';
import toggleTableOperation from '@/mixins/toggleTableOperation';
import * as echarts from "echarts";
import CreateOrUpdateModal from './modal_open.vue';

export default {
  name: 'AlarmConfiguration',
  components: {
    search,
    CreateOrUpdateModal
  },
  mixins: [toggleTableOperation],
  data() {
    return {
      containerHeight: 0,
      params: { current: 1, pageSize: 100000 },
      total: 0,
      chart: null,
      isVisible: false,
      title: '',
      form: {},
      lineData: [],
      deleteShow: false,
      paramsItem: {},
      ids:[],
      columns: [
        {
          title: '对象',
          key: 'orgName',
          tree: true,
          draggable: true,
        },
        {
          title: '简称',
          key: 'orgAbbreviation',
          align: "center",
          draggable: true,
        },
        {
          title: '操作',
          key: 'address',
          slot: "action",
          align: "center",
          fixed: "right",
          draggable: true,
        }
      ],

    };
  },

  mounted() {

    this.listFetch()
    this.chart = echarts.init(this.$refs.chart);
    this.updateContainerHeight();
    window.addEventListener('resize', this.updateContainerHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.updateContainerHeight);
  },
  methods: {
    onDragEnd(newColumns) {
    this.columns = newColumns;
  },    handleSelectionChange(selectionData) {
      console.log(selectionData);
      let arr = [];
      selectionData.forEach(item => {
        arr.push(item.id);
      });
      this.ids = arr;
    },
    handleDeleteSure() {
      deltLine({ids:this.ids}).then(res => {
                    if (res.code === 200) {

                        this.deleteShow = false;
                        this.listFetch()
                    } else {
                        this.$Message.warning(res.message);
                    }
                });

     },
    delShow(row,delType) {
      if(delType==='isAll'){
         this.ids=[row.id]
      }
      this.deleteShow = true
    },
    ShowModal(type, row) {
      if (type !== 'edit') {
        this.form = {}
      } else {
        this.form = { ...row };
      }
      console.log(type, row, 'type,row')
      this.title = type
      this.isVisible = true,
        this.paramsItem = row
    },
    closeModals() {
      this.isVisible = false
    },
    handleAddSubmit() {
      const url = this.form.id ? editLine : addLine;
      let levelNumber = {
       level: 0
      }
      if (this.title === 'add') {
        levelNumber = {
         level: 1,
          parentId: '0'
        }
      } else if (this.title === 'edit') {
        levelNumber = {
         level: this.paramsItem.level,
          parentId: this.paramsItem.parentId
        }
      } else {
        levelNumber = {
         level: this.paramsItem.level + 1,
          parentId: this.paramsItem.id
        }
      }


      const params = {
        ...this.form,
        ...levelNumber,
      }
      url(params).then(res => {

        this.paramsItem = {};
        this.isVisible = false;
        this.listFetch();
      })
        .catch(error => {
          console.error('Error submitting form:', error);

        });

    }
    ,
    buildTree(items) {
      const itemMap = {};
      const rootItems = [];
      items.forEach(item => {
        itemMap[item.id] = { ...item,name:item.orgName, children: [] };
      });
      items.forEach(item => {
        if (!item.parentId || item.parentId === '0') {
          rootItems.push(itemMap[item.id]);
        } else {
          if (itemMap[item.parentId]) {
            itemMap[item.parentId].children.push(itemMap[item.id]);
          }
        }
      });

      return rootItems;
    },
    listFetch() {
      lineAll(this.params).then(res => {
        if (res.code === 200) {
          this.lineData = this.buildTree(res.data.records)
          this.total = res.data.total
          const drawData=this.buildTree(res.data.records)
          console.log(drawData,'drawData')
        this.drawChart(drawData)
        }
      })

    },
    drawChart(data) {


      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          triggerOn: 'mousemove'
        },
        series: [
          {
            type: 'tree',
            data: data,
            top: '1%',
            left: '7%',
            bottom: '1%',
            right: '20%',
            symbolSize: 7,
            label: {
              position: 'left',
              verticalAlign: 'middle',
              align: 'right',
              fontSize: 9
            },
            leaves: {
              label: {
                position: 'right',
                verticalAlign: 'middle',
                align: 'left'
              }
            },
            emphasis: {
              focus: 'descendant'
            },
            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750
          }
        ]
      });

    },
    updateContainerHeight() {
      this.containerHeight = window.innerHeight - 150; // 减去顶部和底部的 padding
    }
  }
};
</script>

<style scoped lang="scss">
.alarmConfiguration {
  display: flex;
  box-sizing: border-box;
  background-color: #f9f9f9;
  border: 1px solid #e5e5e5;

  .button_but_top {
    margin-bottom: 10px;

    button {
      margin: 0 5px;
    }
  }

  .button_but {

    display: flex;

    button {
      margin: 0 1px;
    }
  }

  .left-side,
  .right-side {
    box-sizing: border-box;
    padding: 20px;
    background-color: #f9f9f9;
    border: 1px solid #e5e5e5;
  }

  .left-side {
    max-width: 45%;
    overflow-y: auto;
  }

  .right-side {

    width: 55%;
    overflow-y: auto;
  }

  .left-content,
  .right-content {
    h2 {
      margin-bottom: 10px;
    }
  }
}
</style>
